import { BaseStorageService, PROJECT_CONFIG, StorageConfig } from './storage/baseStorageService';

// 用户设置数据接口
export interface UserSettings {
  id: string;
  theme: 'light' | 'dark';
  language: 'zh-CN' | 'en-US';
  storageType: 'indexedDB' | 'supabase';
  supabaseConfig?: {
    url: string;
    key: string;
  };
  defaultInvestmentAmount: number;
  defaultBuyTimes: number;
  defaultStrategy: string;
  notifications: {
    priceAlert: boolean;
    planReminder: boolean;
    riskWarning: boolean;
  };
  createdAt: string;
  updatedAt: string;
}

// 用户设置服务类 - 继承基础存储服务
class UserSettingsService extends BaseStorageService<UserSettings> {
  private static readonly DEFAULT_SETTINGS_ID = 'user_settings_default';

  constructor(config: StorageConfig = { type: 'indexedDB' }) {
    // 使用项目统一配置中定义的用户设置存储名称
    super(PROJECT_CONFIG.STORE_NAMES.USER_SETTINGS, config);
  }

  // 获取用户设置（基于当前用户）
  async getUserSettings(): Promise<UserSettings> {
    // 验证用户登录状态
    const { getCurrentUserId, isUserAuthenticated } = await import('../utils/userContext');
    if (!(await isUserAuthenticated())) {
      // 如果用户未登录，返回默认设置但不保存
      return this.createDefaultSettings();
    }
    
    const userId = await getCurrentUserId();
    if (!userId) {
      throw new Error('无法获取用户ID');
    }
    
    // 尝试获取用户特定的设置
    const allSettings = await this.getAll();
    let settings = allSettings.find(s => s.id === `user_settings_${userId}`);
    
    if (!settings) {
      // 创建用户特定的默认设置
      settings = this.createDefaultSettings();
      settings.id = `user_settings_${userId}`;
      await this.save(settings);
    }
    
    return settings;
  }

  // 更新用户设置
  async updateUserSettings(updates: Partial<Omit<UserSettings, 'id' | 'createdAt'>>): Promise<void> {
    // 验证用户登录状态
    const { isUserAuthenticated } = await import('../utils/userContext');
    if (!(await isUserAuthenticated())) {
      throw new Error('用户未登录，无法更新用户设置');
    }
    
    const currentSettings = await this.getUserSettings();
    const updatedSettings: UserSettings = {
      ...currentSettings,
      ...updates,
      updatedAt: new Date().toISOString()
    };
    
    await this.save(updatedSettings);
  }

  // 重置为默认设置
  async resetToDefault(): Promise<void> {
    const defaultSettings = this.createDefaultSettings();
    await this.save(defaultSettings);
  }

  // 创建默认设置
  private createDefaultSettings(): UserSettings {
    const now = new Date().toISOString();
    return {
      id: UserSettingsService.DEFAULT_SETTINGS_ID,
      theme: 'light',
      language: 'zh-CN',
      storageType: 'indexedDB',
      defaultInvestmentAmount: 10000,
      defaultBuyTimes: 5,
      defaultStrategy: 'pyramid',
      notifications: {
        priceAlert: true,
        planReminder: true,
        riskWarning: true
      },
      createdAt: now,
      updatedAt: now
    };
  }

  // 获取存储配置
  async getStorageConfigAsync(): Promise<StorageConfig> {
    const settings = await this.getUserSettings();
    return {
      type: settings.storageType,
      supabaseUrl: settings.supabaseConfig?.url,
      supabaseKey: settings.supabaseConfig?.key
    };
  }

  // 更新存储配置
  async updateStorageConfig(config: StorageConfig): Promise<void> {
    await this.updateUserSettings({
      storageType: config.type,
      supabaseConfig: config.supabaseUrl && config.supabaseKey ? {
        url: config.supabaseUrl,
        key: config.supabaseKey
      } : undefined
    });
  }
}

// 创建默认服务实例 - 使用Supabase
export const userSettingsService = new UserSettingsService({
  type: 'supabase',
  supabaseUrl: import.meta.env.VITE_SUPABASE_URL,
  supabaseKey: import.meta.env.VITE_SUPABASE_ANON_KEY
});

// 导出服务类
export { UserSettingsService };